package cn.well.cloud.mutidatasource.aop;

import cn.well.cloud.mutidatasource.DataSourceContextHolder;
import cn.well.cloud.mutidatasource.Enum.DataSourceAddressEnum;
import cn.well.cloud.mutidatasource.annotion.RoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 多数据源切换的aop
 * 2020年4月14日
 * @author wison
 *
 */
@Aspect
@Component
@Slf4j
public class RoutingDataSourceAOP implements Ordered {

    @Pointcut(value = "@annotation(cn.well.cloud.mutidatasource.annotion.RoutingDataSource)")
    private void routingDataSourcePointcut() {

    }

    @Around("routingDataSourcePointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Signature signature = point.getSignature();
        MethodSignature methodSignature = null;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;

        Method method = methodSignature.getMethod();
        RoutingDataSource routerDataSource = method.getAnnotation(RoutingDataSource.class);
        // 如果没有设置则默认为 MASTER
        DataSourceAddressEnum dataSourceAddressEnum = Objects.isNull(routerDataSource) ? DataSourceAddressEnum.MASTER : routerDataSource.value();
        DataSourceContextHolder.setCurrentDataSource(dataSourceAddressEnum);
        log.debug("设置数据源为：" + DataSourceContextHolder.getCurrentDataSource());
        try {
            return point.proceed();
        } finally {
            log.debug("清空数据源信息！");
            DataSourceContextHolder.clearDataSourceType();
        }
    }


    /**
     * aop的顺序要早于spring的事务
     */
    @Override
    public int getOrder() {
        return 1;
    }

}
